package com.lsk.admin.order;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import com.lsk.util.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderService
{
    public Map orderListDataService(int page, int limit, String state)
    {
        String sql = "SELECT *from shop_order ";
        if (!state.equals("")) {
            sql = sql + " where state='" + state + "' ";
        }
        sql = sql + " ORDER BY createTime desc  ";

        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        for (int i = 0; i < list.size(); i++)
        {
            Record record = (Record)list.get(i);
            state = record.getStr("state");
            if ("0".equals(state)) {
                record.set("state", "未支付");
            } else if ("1".equals(state)) {
                record.set("state", "已支付");
            } else if ("2".equals(state)) {
                record.set("state", "待收货");
            } else {
                record.set("state", "已结束");
            }
            list.set(i, record);
        }
        Map map = new HashMap();
        map.put("code", Integer.valueOf(0));
        if (count > 0)
        {
            map.put("count", Integer.valueOf(count));
            map.put("data", list);
        }
        else
        {
            map.put("count", Integer.valueOf(0));
            map.put("msg", "暂无数据");
        }
        return map;
    }

    public Record getOrderById(String id)
    {
        String sql = "SELECT *from shop_order where id='" + id + "'";

        Record order = Db.findFirst(sql);

        return order;
    }

    public List<Record> getOrderInfoList(String orderId)
    {
        String infoSql = "SELECT *from shop_order_info where orderId='" + orderId + "'";

        List<Record> infoList = Db.find(infoSql);

        return infoList;
    }

    public Record getLogisticsInfo(String orderId)
    {
        String sql = "SELECT *from shop_logistics where orderId='" + orderId + "' ";
        Record record = Db.findFirst(sql);
        if (record != null)
        {
            Object object = record.get("apiMessage");
            String apiMessage = record.getStr("apiMessage");
            Map<String, Object> map = (Map) JsonUtils.parse(apiMessage, Map.class);
            List infoList = (List)map.get("list");
            record.remove("apiMessage").set("infoList", infoList);
            String state = record.getStr("state");
            if (("3".equals(state)) || ("4".equals(state)))
            {
                Syslog.info("订单号:" + orderId + "的状态为" + state);
            }
            else
            {
                Date upTime = record.getDate("upTime");
                Date now = new Date();

                long timeInterval = now.getTime() - upTime.getTime();
                Syslog.info(Long.valueOf(timeInterval));
                if (timeInterval > 10800000L)
                {
                    String id = record.getStr("id");
                    String result = ExpressageUtil.getInfo(id);
                    System.out.println(result);
                    Map<String, Object> resultMap = (Map) JsonUtils.parse(result, Map.class);

                    record = new Record().set("id", UtilUUID.getUUID()).set("logisticsId", id).set("orderId", orderId).set("apiMessage", result).set("upTime", new Date()).set("state", resultMap.get("state")).set("name", resultMap.get("name")).set("site", resultMap.get("site")).set("phone", resultMap.get("phone")).set("logo", resultMap.get("logo")).set("code", resultMap.get("code"));
                    Db.update("shop_logistics", "id", record);

                    map = (Map) JsonUtils.parse(result, Map.class);
                    infoList = (List)map.get("list");
                    record.remove("apiMessage").set("infoList", infoList);
                }
                record = Db.findFirst(sql);
            }
        }
        return record;
    }

    public ReturnData saveLogisticsService(String id, String orderId)
    {
        ReturnData returnData = null;
        boolean sa = false;

        String result = ExpressageUtil.getInfo(id);
        System.out.println(result);
        Map<String, Object> resultMap = (Map) JsonUtils.parse(result, Map.class);

        Record logistics = new Record().set("logisticsId", id).set("orderId", orderId).set("apiMessage", result).set("upTime", new Date()).set("state", resultMap.get("state")).set("name", resultMap.get("name")).set("site", resultMap.get("site")).set("phone", resultMap.get("phone")).set("logo", resultMap.get("logo")).set("code", resultMap.get("code"));

        String sql = "SELECT *from shop_logistics where  orderId='" + orderId + "' ";

        Record record = Db.findFirst(sql);
        if (record == null)
        {
            logistics.set("id", UtilUUID.getUUID());
            sa = Db.save("shop_logistics", "id", logistics);
        }
        else
        {
            logistics.set("id", record.getStr("id"));
            sa = Db.update("shop_logistics", "id", logistics);
        }
        return new ReturnData(sa);
    }

    public Record getAddressById(String id)
    {
        String sql = "SELECT * from yx_member_address where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    public ReturnData saveEditOrderService(Map<String, String[]> map)
    {
        String id = ((String[])map.get("id"))[0];
        String state = ((String[])map.get("state"))[0];
        String remark = ((String[])map.get("remark"))[0];
        String detailInfo = ((String[])map.get("addressInfo"))[0];
        String addressTel = ((String[])map.get("addressTel"))[0];
        String addressName = ((String[])map.get("addressName"))[0];
        String provinceName = ((String[])map.get("provinceName"))[0];
        String cityName = ((String[])map.get("cityName"))[0];
        String countyName = ((String[])map.get("countyName"))[0];

        Record record = new Record().set("id", id).set("state", state).set("remark", remark).set("addressInfo", provinceName + cityName + countyName + detailInfo).set("addressTel", addressTel);

        boolean sa = Db.update("shop_order", "id", record);

        return new ReturnData(sa);
    }

    public Map memberUpVIPDataServce(int page, int limit)
    {
        String sql = "SELECT * from sys_order ORDER BY createTime desc  ";
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        for (int i = 0; i < list.size(); i++)
        {
            Record record = (Record)list.get(i);
            String state = record.getStr("state");
            if ("0".equals(state)) {
                record.set("state", "未支付");
            } else if ("1".equals(state)) {
                record.set("state", "已支付");
            }
            String memberId = record.getStr("memberId");

            String parentId = record.getStr("parentId");

            String memberSql = "SELECT *from yx_member where id= ";

            Record memberInfo = Db.findFirstByCache("oneHour",
                    MD5.md5(memberSql + " '" + memberId + "' "), memberSql + " '" + memberId + "' ");
            if (memberInfo != null) {
                record.set("memberName", memberInfo.getStr("name")).set("rebateMoney", memberInfo.getStr("rebateMoney")).set("oneSonMember", memberInfo.getStr("oneSonMember")).set("twoSonMember", memberInfo.getStr("twoSonMember")).set("accountMoney", memberInfo.getStr("accountMoney")).set("grade", memberInfo.getInt("grade").intValue() == 0 ? "��������" : "VIP");
            }
            Record parentInfo = Db.findFirstByCache("oneHour",
                    MD5.md5(memberSql + " ' " + parentId + "'"), memberSql + "'" + parentId + "' ");
            if (parentInfo != null) {
                record.set("parentName", parentInfo.getStr("name"));
            }
            list.set(i, record);
        }
        Map map = new HashMap();
        map.put("code", Integer.valueOf(0));
        if (count > 0)
        {
            map.put("count", Integer.valueOf(count));
            map.put("data", list);
        }
        else
        {
            map.put("count", Integer.valueOf(0));
            map.put("msg", "暂无数据");
        }
        return map;
    }

    public ReturnData delOrder(String orderId)
    {
        Record order = getOrderById(orderId);

        boolean del = Db.delete("shop_order", "id", order);

        return new ReturnData(del);
    }

    public PageUtil orderManagement(String page, String limit,String shop,String spotName,String visitPhone,String checkCode,String personType,String startTime,String overTime,String checkStatus)
    {
//        String sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
//        if ((type != null) && (!"".equals(type))) {
//            sql = sql + "and a.state='" + type + "'";
//        }
//        if ((id != null) && (!"".equals(id))) {
//            sql = sql + "and a.id='" + id + "'";
//        }
        String sql="";
        if ((shop != null) && (!"".equals(shop))) {
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.shopId = '"+ shop +"'";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
            sql = sql + "  ORDER BY rr.createTime DESC";
        }
        if ((checkCode != null) && (!"".equals(checkCode))) {
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.personType,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
            sql = sql + "and a.checkCode= '" + checkCode + "'";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
//            sql = sql + "  ORDER BY rr.createTime DESC";
        }

        if ((visitPhone != null) && (!"".equals(visitPhone))) {
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
            sql = sql + "and a.visitPhone= '" + visitPhone + "'";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
//            sql = sql + "  ORDER BY rr.createTime DESC";
        }

        if ((personType != null) && (!"".equals(personType))) {
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
            sql = sql + "and a.personType= '" + personType + "'";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
            sql = sql + "  ORDER BY rr.createTime DESC";
        }

        if ((checkStatus != null) && (!"".equals(checkStatus))) {
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
            sql = sql + "and a.checkStatus= '" + checkStatus + "'";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
            sql = sql + "  ORDER BY rr.createTime DESC";
        }

        if ((startTime!=null)&&(!"".equals(startTime))&&(overTime!=null)&&(!"".equals(overTime))){
            sql = "SELECT rr.*,yx.`name` as fenxiaoName from \n(\nSELECT\n\ta.id,\n\ta.money,\n\ta.state,\n\ta.checkCode,\n\ta.checkStatus,\n\ta.endTime,\n\ta.spotName,\n\ta.createTime,\n\ta.number,\n\tb.`name` AS memberName,\n\ta.visitPhone AS tel, a.visitName as visitName, yma.detailInfo as address ,a.visitIdnumber as visitIdnumber ,\n\tc.`name` AS ticketName,\n\ta.parentId as memberId,\n\ta.deliverystatus\n\nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\nLEFT JOIN ticket c ON a.commodityId = c.id\n   left join  yx_member_address yma on  yma.memberId=b.id \nWHERE a.spotName = '"+ spotName +"'";
            sql = sql + "and a.createTime>= '" + startTime + "' and a.endTime<='"+overTime +"' ";
            sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
            sql = sql + "  ORDER BY rr.createTime DESC";
        }
//        if (((id != null) && (!"".equals(id))) || ((visitPhone != null) && (!"".equals(visitPhone)))) {
//            sql = sql + " and a.id='" + id + "' and b.tel='" + visitPhone + "'";
//        }
//        sql = sql + "  ) rr LEFT JOIN yx_member yx  on rr.memberId=yx.id  ";
////        if ((fenxiaoName != null) && (!"".equals(fenxiaoName))) {
////            sql = sql + "and rr.name='" + fenxiaoName + "'";
////        }
//        sql = sql + "  ORDER BY rr.createTime DESC";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql);
        return pageUtil;
    }


    public List<Record> fenxiaoMember()
    {
        String sql = "SELECT\n\td.`name`,d.id\n  \nFROM\n\tyx_order a\nLEFT JOIN yx_member b ON a.memberId = b.id\n LEFT JOIN yx_member d ON b.parentId=d.id\nLEFT JOIN ticket c ON a.commodityId = c.id\nWHERE\n\ta.shopId = '4b648bbc537e4cc19942827a2a9dc8d4' GROUP BY d.id ORDER BY a.createTime DESC";

        List<Record> list = Db.find(sql);

        return list;
    }

    public PageUtil applyRefund(String page, String limit, String userId, String memberName)
    {
        String shopSql = "SELECT * FROM shop WHERE sys_user_id='" + userId + "'";
        Record record = Db.findFirst(shopSql);

        String shopId = (String)record.get("id");
        String sql = " SELECT * from  yx_apply_refund  where shopId='" + shopId + "' ";
        String countSql = "SELECT count(id) from  yx_apply_refund  where shopId='" + shopId + "' ";
        if ((memberName != null) && (!"".equals(memberName)))
        {
            sql = sql + " and memberName LIKE '%" + memberName + "%'";
            countSql = countSql + " and memberName LIKE '%" + memberName + "%'";
        }
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    public ReturnData editapplyRefund(Map<String, String[]> map)
    {
        String id = ((String[])map.get("id"))[0];
        String state = ((String[])map.get("sta"))[0];
        String sql = " SELECT * from  yx_apply_refund  where id='" + id + "' ";
        Record record = Db.findFirst(sql);
        record.remove("state");
        record.set("state", state);
        boolean sa = Db.update("yx_apply_refund", record);
        return new ReturnData(sa);
    }
}
